package com.sise.dubbo.redislock.service;

import com.sise.dubbo.redislock.constants.RedisKeyPrefix;
import com.sise.dubbo.redislock.dto.GoodsDTO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author idea
 * @data 2019/2/2
 */
@Service
public class GoodsService {


    @Resource
    private RedisTemplate<String, GoodsDTO> redisTemplate;


    public void exchangeGoods(int id) {
        String key = RedisKeyPrefix.GOODS + id;
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            GoodsDTO goodsDTO = redisTemplate.opsForValue().get(key);
            if (goodsDTO.getCount() > 0) {
                goodsDTO.setCount(goodsDTO.getCount() - 1);
                //还原库存信息
                redisTemplate.opsForValue().set(key, goodsDTO);
                System.out.println("抢购成功，库存扣1");
            } else {
                System.out.println("库存不足");
            }
        } else {
            GoodsDTO goodsDTO = new GoodsDTO();
            goodsDTO.setCount(10);
            goodsDTO.setGoodName("牛奶");
            goodsDTO.setId(id);
            redisTemplate.opsForValue().set(key, goodsDTO);
        }
    }
}
